<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="$t('product.setting.qrCodeSet.associateDialog.title1')"
    :before-close="handleClose"
    width='70%'
  >
    <div class="dialog-top">
      <div>
        <el-button type="primary" @click="openRelation">{{$t('product.setting.qrCodeSet.associateDialog.btn1')}}</el-button>
        <el-button type="plain-third" @click="unRelation">{{$t('product.setting.qrCodeSet.associateDialog.btn2')}}</el-button>
      </div>

      <el-input :placeholder="$t('product.setting.qrCodeSet.associateDialog.pla2')" v-model="params.keywords" prefix-icon="el-icon-search">
        <el-button slot='append' type='primary' @click="search">{{$t('common.base.search')}}</el-button>
      </el-input>
    </div>

    <el-table
      :data='page.list'
      border
      stripe
      @select="handleSelection"
      @select-all="handleSelection"
      class="dialog-table"
      ref="multipleTable"
      header-row-class-name="common-list-table-header"
    >
      <el-table-column
        type="selection"
        align="center"
        width="55">
      </el-table-column>
      <template v-for="item in columns">
        <el-table-column
          :label='item.name' 
          :key="item.prop"
          :prop='item.prop'
          :min-width='item.minWidth'
          :width='item.width'
        >
          <template slot-scope="scope">
            <!--start 产品类型编号 -->
            <template v-if="item.prop === 'catalogNum'">
              <a
                  class="color-primary"
                  v-if="catalogViewAuth"
                  style="cursor:pointer;"
                  @click.stop.prevent="toDetail(scope.row.id)">
                {{ scope.row[item.prop] || '' }}
              </a>
              <template v-else>{{scope.row[item.prop] || ''}}</template>
            </template>
            <!--end 产品类型编号 -->
            <template v-else-if="item.prop === 'createTime'">
              {{ formatDate(scope.row[item.prop], 'YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <div class="table-footer">
      <div class="list-info">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{ page.total }}</span>
        </i18n>
        <template v-if="multipleSelection&&multipleSelection.length>0">
          <i18n path="common.base.table.selectedNth">
          <span place="count">{{ multipleSelection.length }}</span>
        </i18n>
          <span class="catalog-selected-count"
                @click="toggleSelection()">{{$t('common.base.clear')}}</span>
        </template>
      </div>
      <el-pagination class="product-table-pagination"
        background
        @current-change="jump"
        @size-change="handleSizeChange"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="page.pageSize"
        :current-page="page.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="page.total">
      </el-pagination>
    </div>

    <el-dialog :title="$t('product.setting.qrCodeSet.associateDialog.title2')" append-to-body :visible.sync="showAdd" width="400px">
      <div>
        {{$t('product.setting.qrCodeSet.associateDialog.label1')}}：
        <el-cascader
          :placeholder="$t('product.setting.qrCodeSet.associateDialog.pla1')"
          popperClass='cascader-checkbox'
          @visible-change='cascaderVisibleChange'
          style="width:calc(100% - 100px)"
          v-model="catalog"
          :options='treeList'
          :show-all-levels="false"
          expand-trigger="hover"
          clearable
          :props="props"
          filterable
          collapse-tags
        ></el-cascader>
      </div>
      <span slot="footer">
        <el-button @click="showAdd = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="relationProductCatalog">{{$t('common.base.confirm')}}</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  getAllProductCatalog,
  getAllProductCatalogIds,
  cancelRelationProductCatalog,
  relationProductCatalog,
} from '@src/api/SuperQrcode';
import {cloneData} from '@src/api/ProductV2Api';
import _ from 'lodash';
import {Cascader} from 'element-ui';
import {clickLabel} from '@src/util/function';
import { openAccurateTab } from '@src/util/platform'
import { defaultTableData } from '@src/util/table'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales'
import { formatDate } from 'pub-bbx-utils';
export default {
  name:'associate-dialog',
  data(){
    return{
      defaultTableData,
      dialogVisible:false,
      params:{
        tenantId:'',
        templateId:'',
        keywords:'',
        pageNum:1,
        pageSize:10
      },
      page:{
        list:[]
      },
      columns:[
        {
          prop:'catalogNum',
          name:i18n.t('common.base.column.prodcutTypeNum'),
          minWidth:'110px',
          width:'110px'
        },
        {
          prop:'pathName',
          name:i18n.t('common.base.column.classification'),
          minWidth:'100px'
        },
        {
          prop:'catalogName',
          name:i18n.t('common.base.column.prodcutTypeName'),
          minWidth:'110px'
        },
        {
          prop:'productNum',
          name:i18n.t('common.base.column.productCount'),
          minWidth:'80px',
          width:'80px'
        },
        {
          prop:'createTime',
          name:i18n.t('common.base.column.createTime'),
          width:'180px'
        },
        {
          prop:'displayName',
          name:i18n.t('common.base.column.createPerson'),
          minWidth:'100px'
        }
      ],
      multipleSelection:[],
      showAdd:false,
      catalog:[],
      props:{
        multiple:true,
        value:'id',
        label:'name',
        children:'tasks',
      },
      treeList:[]
    }
  },
  props:{
    tenantId:{
      type:String,
      default:''
    },
    catalogViewAuth:{
      type:Boolean,
      default:false
    }
  },
  mounted(){
    clickLabel('cascader-checkbox');
  },
  methods: {
    formatDate,
    // 级联选择器打开/关闭
    cascaderVisibleChange(val){
      if(val){
        this.$nextTick(()=>{
          document.getElementsByClassName('el-cascader__dropdown')[0].style.zIndex='9999';
        })
      }else{
        this.$nextTick(()=>{
          document.getElementsByClassName('el-cascader__dropdown')[0].style.zIndex='1';
        })
      }
      
    },
    // 获取树结构
    async getTreeList(){
      try{
        let {code,result,message}=await cloneData();
        if(code===0){
          this.deleteEmpty(result);
          this.treeList=result;
        }else{
          this.$platform.notification({
            type: 'error',
            title: i18n.t('common.base.tip.httpIsError'),
            message: message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty(list){
      list.forEach(item=>{
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
    // 打开关联弹窗
    openRelation(){
      this.showAdd=true;
      this.catalog = []
      this.getAllProductCatalogIds()
    },
    // 关联
    async relationProductCatalog(){
      if(!this.catalog.length){
        return this.$message.warning(this.$t('product.setting.qrCodeSet.associateDialog.tips1'));
      }
      const catalogIds=this.catalog.map(item=>item[item.length-1]);
      const params={
        tenantId:this.tenantId,
        templateId:this.params.templateId,
        catalogIds
      }
      let {code,msg}=await relationProductCatalog(params);
      if(code==='200'){
        this.showAdd=false;
        this.search(true);
        this.$emit('relation');
      }else{
        this.$platform.notification({
          type: 'error',
          title: this.$t('common.base.tip.httpIsError'),
          message: msg
        })
      }
    },
    // 取消关联
    unRelation(){
      if(!this.multipleSelection.length){
        return this.$message.warning(this.$t('product.setting.qrCodeSet.associateDialog.unRelation.tips1'));
      }
      this.$confirm(this.$t('product.setting.qrCodeSet.associateDialog.unRelation.tips2'),this.$t('common.base.toast'),{
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(()=>{
        const params={
          tenantId:this.tenantId,
          templateId:this.params.templateId,
          catalogIds:this.multipleSelection.map(item=>item.id)
        }
        cancelRelationProductCatalog(params).then(res=>{
          if(res.code==='200'){
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.toast'),
              message: res.msg
            });
            this.search(true);
            this.$emit('relation');
          }else{
            this.$platform.notification({
              type: 'error',
              title: this.$t('common.base.tip.httpIsError'),
              message: res.msg
            });
          }
        });
      }).catch(()=>{})
    },
    toDetail(id){
      let fromId;
      try {
        fromId = window.frameElement.getAttribute('id');
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      // this.$platform.openTab({
      //   id: `productV2_catalog_view_${id}`,
      //   title: '产品类型详情',
      //   close: true,
      //   url: `/productV2/catalog/view?id=${id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        fromId
      })
    },
    open(){
      this.dialogVisible=true;
      const pageSize=localStorage.getItem('qrcodeSet_associate_pageSize');
      this.params.pageSize=pageSize?Number(pageSize):10;
      this.params.tenantId=this.tenantId;
      this.params.templateId=sessionStorage.getItem('qrcode_associate_templateId');
      this.params.pageNum=1;
      this.search();
      this.getTreeList();
    },
    jump(pageNum){
      this.params.pageNum=pageNum;
      this.search();
    },
    handleSelection(selection){
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter((ms) =>
        this.page.list.some((cs) => cs.id === ms.id)
      );

      let unSelected = this.page.list.filter((c) =>
        original.every((oc) => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach((row) => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.choiceLimit', {limit:this.selectedLimit}));
      }

      this.multipleSelection = tv;
    },
    // 计算已选择
    selectionCompute (selection) {
      let tv = [];

      tv = this.multipleSelection.filter((ms) =>
        this.page.list.every((c) => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    // 匹配选中的列
    matchSelected () {
      if (!this.multipleSelection.length) return;

      const selected = this.page.list.filter((c) => {
        if (this.multipleSelection.some((sc) => sc.id === c.id)) {
          this.multipleSelection = this.multipleSelection.filter(
            (sc) => sc.id !== c.id
          );
          this.multipleSelection.push(c);
          return c;
        }
      }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    handleSizeChange(pageSize){
      localStorage.setItem('qrcodeSet_associate_pageSize',pageSize);
      this.params.pageSize=pageSize;
      this.search();
    },
    // 清空
    toggleSelection(rows){
      let isNotOnCurrentPage = false;
      let row = undefined;
      if(rows){
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every((item) => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      }else{
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    // 获取数据
    async search(refresh=false){
      try{
        if(refresh===true){
          this.params.keywords='';
          this.params.pageNum=1;
          this.multipleSelection=[];
        }
        let {code,data,msg}=await getAllProductCatalog(this.params);
        if(code==='200'){
          this.page=data;
          this.matchSelected();
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: msg
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    async getAllProductCatalogIds() {
      try{
        let params = {
          tenantId: this.params.tenantId,
          templateId: this.params.templateId
        }
        let { code, data, msg } = await getAllProductCatalogIds(params);
        if(code === '200'){
          this.catalog = data || [];
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: msg
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    handleClose(){
      this.params.pageNum=1;
      this.params.keywords='';
      this.multipleSelection=[];
      this.dialogVisible=false;
    },
    submit(){}
  },
  components:{
    [Cascader.name]: Cascader
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-cascader__search-input{
  margin:2px 0 2px 12px;
}
::v-deep .el-dialog__body{
  padding: 10px 20px;
}
::v-deep .el-input-group__append{
  color: #fff;
  background-color: $color-primary;
  border: 1px solid $color-primary;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}
::v-deep .el-input-group{
  width: 250px;
}
::v-deep .el-input-group--append{
  .el-input__inner{
    border-top-left-radius:4px;
    border-bottom-left-radius: 4px;
  }
  .el-input-group__append{
    border-top-left-radius: 0;
    border-bottom-left-radius:0;
  }
}
::v-deep .el-dialog__footer{
  border-top: 1px solid $color-border-l3;
}

.dialog-top{
  display: flex;
  justify-content: space-between;
}
.dialog-table{
  margin: 10px 0;
}
.catalog-selected-count{
  color:$color-primary;
  cursor: pointer;
}
</style>